(function() {
  app.service('canvas', ['$rootScope', '$window', 'quoteApi', function($rootScope, $window, quoteApi) {
    this.canvas = function(stkinfo) {
      angular.element(document).ready(function() {
        var figurecan = $('#figurecan');
        figurecan.attr('width', 750);
        figurecan.attr('height', 543);

        var stockCode = stkinfo.code;
        var market = stkinfo.market;

        figureCanvas();

        function figureCanvas() {
          var transData = {};
          var transData_data = [];
          var chart_info = [];
          var data_ = {};
          var fenshi_last_point = null;

          var df = new quoteApi.QuoteApi.DftMin0x25({
            code: stockCode,
            market: market,
          });
          quoteApi.query(df).then(function(data) {
            transData.fp = data.close;
            for (var i = 0; i < data.detail.length; i++) {
              var arr1 = [];
              arr1[0] = (data.detail)[i].price;
              arr1[1] = 0;
              arr1[2] = (data.detail)[i].volume;
              arr1[3] = (data.detail)[i].avg_price;
              transData_data.push(arr1);

            }

            transData.data = transData_data;
            transData.tol_vol = data.total_vol;
            transData.tol_sum = data.total_sum;
            canvasBorder('figurecan', transData);
          });
          var co = document.getElementById('figurecan');
          if (!co) return;
          var canvasw = co.width - 5;
          var canvash = co.height;
          var oGc = co.getContext('2d');
          $(co).off();

          $(co).on('click', function(evt) {
            if (!fenshi_last_point) return;
            var mousePos = getMousePos(co, evt);
            var x = mousePos.x;
            var y = mousePos.y;
            var time;
            if (x > fenshi_last_point[0]) {
              x = fenshi_last_point[0];
              y = fenshi_last_point[1];
            }
            var clickIndex = Math.round(x / (canvasw / 240));
            var fenshi_data_y = canvash / 4 + canvash / 4 / (data_.fp * data_.percent) * (data_.fp - chart_info[1][clickIndex]);

            oGc.clearRect(1, 1, canvasw, canvash);
            canvasBorder('figurecan', transData);
            oGc.beginPath();
            oGc.strokeStyle = '#888888';
            oGc.lineWidth = 2;
            oGc.moveTo(0.5, fenshi_data_y);
            oGc.lineTo(0.5 + canvasw, fenshi_data_y);
            oGc.stroke();
            var min_;
            var hour_;
            if (x / canvasw <= 0.5) {
              hour_ = parseInt(((x / canvasw * 240) + 30) / 60);
              min_ = (parseInt(x / canvasw * 240) + 30) % 60 < 10 ? '0' + (parseInt(x / canvasw * 240) + 30) % 60 : (parseInt(x / canvasw * 240) + 30) % 60;
            } else {
              hour_ = parseInt(((x / canvasw * 240) + 30 - 150) / 60);
              min_ = (parseInt(x / canvasw * 240) + 30 - 150) % 60 < 10 ? '0' + (parseInt(x / canvasw * 240) + 30 - 150) % 60 : (parseInt(x / canvasw * 240) + 30 - 150) % 60;
            }
            x / canvasw <= 0.5 ? time = hour_ + 9 + ':' + min_ : time = hour_ + 13 + ':' + min_;
            oGc.strokeStyle = '#888888';
            oGc.lineWidth = 2;
            oGc.moveTo(x, 0.5);
            oGc.lineTo(x, canvash / 2 + canvash / 20 + canvash / 3);
            oGc.font = '25px Courier New solid';
            oGc.fillText(time, canvasw / 2 - 35, canvash);
            oGc.stroke();
            oGc.closePath();
            drawfont('25px', oGc, ((chart_info[1][clickIndex] - transData.fp) / transData.fp * 100).toFixed(2) + '%', canvasw - 80, fenshi_data_y < (canvash / 6) ? fenshi_data_y + 30 : fenshi_data_y - 10);
            drawfont('25px', oGc, chart_info[1][clickIndex].toFixed(2), canvasw / 250, fenshi_data_y < (canvash / 6) ? fenshi_data_y + 30 : fenshi_data_y - 10);
            oGc.clearRect(190 * canvasw / 500, canvash / 2 + 1, 100000, canvash / 22);
            drawfont('25px', oGc, '现手:' + unita(chart_info[0][clickIndex]), 190 * canvasw / 500, canvash / 2 + 90 / 4);
          });
          $(co).on('touchmove', function(evt) {
            var co = document.getElementById('figurecan');
            if (!co) return;
            var canvasw = co.width - 5;
            var canvash = co.height;
            evt.preventDefault();
            var touch = evt.touches[0]; //获取第一个触点
            var _x = Number(touch.pageX); //页面触点X坐标
            var _y = Number(touch.pageY); //页面触点Y坐标
            var rect = co.getBoundingClientRect();
            var x = (_x - rect.left) * (co.width / rect.width);
            var y = (_y - rect.top) * (co.height / rect.height);
            if (x > fenshi_last_point[0]) {
              x = fenshi_last_point[0];
              y = fenshi_last_point[1];
            }
            oGc.clearRect(1, 1, canvasw, canvash);
            canvasBorder('figurecan', transData);
            oGc.beginPath();
            oGc.strokeStyle = '#888888';
            oGc.lineWidth = 2;
            oGc.moveTo(x, 0.5);
            oGc.lineTo(x, canvash / 2 + canvash / 20 + canvash / 3);
            oGc.stroke();
            oGc.closePath();
            var clickIndex = Math.round(x / (canvasw / 240));
            if (chart_info[1][clickIndex] == undefined) return;
            var fenshi_data_y = canvash / 4 + canvash / 4 / (data_.fp * data_.percent) * (data_.fp - chart_info[1][clickIndex]);
            var min_, time, hour_;
            min_ = (parseInt(x / canvasw * 240) + 30) % 60 < 10 ? '0' + (parseInt(x / canvasw * 240) + 30) % 60 : (parseInt(x / canvasw * 240) + 30) % 60;
            if (x / canvasw <= 0.5) {
              hour_ = parseInt(((x / canvasw * 240) + 30) / 60);
              min_ = (parseInt(x / canvasw * 240) + 30) % 60 < 10 ? '0' + (parseInt(x / canvasw * 240) + 30) % 60 : (parseInt(x / canvasw * 240) + 30) % 60;
            } else {
              hour_ = parseInt(((x / canvasw * 240) + 30 - 150) / 60);
              min_ = (parseInt(x / canvasw * 240) + 30 - 150) % 60 < 10 ? '0' + (parseInt(x / canvasw * 240) + 30 - 150) % 60 : (parseInt(x / canvasw * 240) + 30 - 150) % 60;
            }
            x / canvasw <= 0.5 ? time = hour_ + 9 + ':' + min_ : time = hour_ + 13 + ':' + min_;
            oGc.beginPath();
            oGc.strokeStyle = '#888888';
            oGc.lineWidth = 2;
            oGc.moveTo(0.5, fenshi_data_y);
            oGc.lineTo(0.5 + canvasw, fenshi_data_y);
            oGc.stroke();
            oGc.font = '25px Courier New solid';
            oGc.fillText(time, canvasw / 2 - 35, canvash);
            oGc.stroke();
            oGc.closePath();
            drawfont('25px', oGc, ((chart_info[1][clickIndex] - transData.fp) / transData.fp * 100).toFixed(2) + '%', canvasw - 80, fenshi_data_y < (canvash / 6) ? fenshi_data_y + 30 : fenshi_data_y - 10);
            drawfont('25px', oGc, chart_info[1][clickIndex].toFixed(2), canvasw / 250, fenshi_data_y < (canvash / 6) ? fenshi_data_y + 30 : fenshi_data_y - 10);
            oGc.clearRect(190 * canvasw / 500, canvash / 2 + 1, 100000, canvash / 22);
            drawfont('25px', oGc, '现手:' + unita(chart_info[0][clickIndex]), 190 * canvasw / 500, canvash / 2 + 90 / 4);
          });

          function canvasBorder(de, data) {
            chart_info[0] = [];
            chart_info[1] = [];
            chart_info[2] = [];
            data_.fp = data.fp;
            //获取canvas元素
            var co = document.getElementById(de);
            if (!co) return;
            var canvasw = co.width - 5;
            var canvash = co.height;
            var oGc = co.getContext('2d');
            oGc.clearRect(1, 1, canvasw, canvash);
            //计算生成文字线柱的高度
            var maxk = 0,
              maxl = 0;
            var mink = 1 / 0,
              minl = 0;
            var n = data.data.length;
            for (var i = 1; i < n; i++) {
              //找到现价的最大值和最小值
              if (maxk < data.data[i][0]) {
                maxk = data.data[i][0];
              }
              if (mink > data.data[i][0]) {
                mink = data.data[i][0];
              }
              if (maxk < data.data[i][3]&& data.data[i][3]!=0) {
                maxk = data.data[i][3];
              }
              if (mink > data.data[i][3]&& data.data[i][3]!=0) {
                mink = data.data[i][3];
              }
              //找到成交量的最大值和最小值
              if (maxl < data.data[i][2]) {
                maxl = data.data[i][2];
              }
              if (minl > data.data[i][2]) {
                minl = data.data[i][2];
              }
            }
            // maxk += data.data[0][0] * 0.01;
            // mink -= data.data[0][0] * 0.01;
            var percent = 0;
            if (maxk - data.fp > data.fp - mink) {
              percent = (maxk - data.fp) / data.fp;
            } else {
              percent = (data.fp - mink) / data.fp;
            }
            data_.percent = percent;
            //分时线蓝色背景
            oGc.beginPath();
            oGc.strokeStyle = '#d4e1f1';
            oGc.lineWidth = canvasw / 240;
            oGc.moveTo(1, canvash / 4 + canvash / 4 / (data.fp * percent) * (data.fp - data.data[0][0]));
            //循环写下一个点的坐标
            for (i = 1; i < data.data.length - 1; i++) {
              var top = canvash / 4 + canvash / 4 / (data.fp * percent) * (data.fp - data.data[i][0]);
              oGc.lineTo(i * canvasw / 240, top);
            }
            oGc.lineTo(i * canvasw / 240, canvash / 2);
            oGc.lineTo(1, canvash / 2);
            oGc.fillStyle = 'red';
            oGc.closePath();
            var linearGradient1 = oGc.createLinearGradient(0, canvash / 2, 0, 0);
            linearGradient1.addColorStop(0, '#fff');
            linearGradient1.addColorStop(0.2, '#fff');
            linearGradient1.addColorStop(0.5, '#d4e1f1');
            linearGradient1.addColorStop(1, '#d4e1f1');
            oGc.fillStyle = linearGradient1;
            oGc.fill();
            oGc.stroke();
            //生成两个矩形框
            oGc.beginPath();
            oGc.strokeStyle = '#f5f5f5';
            oGc.strokeRect(0.5, 0.5, canvasw, canvash / 2 + 0.5);
            oGc.strokeRect(0.5, canvash / 2 + canvash / 20, canvasw, canvash / 3);
            //生成十字虚线
            drawDashLine(oGc, 2.5, canvash / 4, canvasw, canvash / 4, 5);
            drawDashLine(oGc, canvasw / 2, 2.5, canvasw / 2, canvash / 2, 5);
            drawDashLine(oGc, 2.5, canvash / 60 * 43, canvasw, canvash / 60 * 43, 5);
            drawDashLine(oGc, canvasw / 2, canvash / 2 + canvash / 20, canvasw / 2, canvash * 0.89, 5);
            oGc.stroke();
            // 生成文字
            drawfont('25px', oGc, (data.fp + (data.fp * percent)).toFixed(2), canvasw / 230 / 4, 36 * canvash / 610, '#f60300');
            drawfont('25px', oGc, (data.fp - (data.fp * percent)).toFixed(2), canvasw / 230 / 4, canvash / 2 - 10, '#30ae0e');
            drawfont('25px', oGc, (percent * 100).toFixed(2) + '%', canvasw - 240 / 3, 36 * canvash / 610, '#f60300');
            drawfont('25px', oGc, (-percent * 100).toFixed(2) + '%', canvasw - 260 / 3, canvash / 2 - 10, '#30ae0e');
            drawfont('25px', oGc, '9:30', canvasw / 250, canvash - canvash / 15);
            drawfont('25px', oGc, '11:30/13:00', 190 * canvasw / 500, canvash - canvash / 15);
            drawfont('25px', oGc, '15:00', canvasw - 240 / 4, canvash - canvash / 15);
            drawfont('25px', oGc, '成交量:' + unita(data.tol_vol), canvasw / 250, canvash / 2 + 90 / 4);
            oGc.clearRect(190 * canvasw / 500, canvash / 2 + 1, 100000, canvash / 22);
            drawfont('25px', oGc, '现手:' + unita(data.data[data.data.length - 1][2]), 190 * canvasw / 500, canvash / 2 + 90 / 4);
            drawfont('25px', oGc, unita(maxl), 0.5, canvash / 2 + canvash / 20 * 2);
            if (maxl != 0)
              drawfont('25px', oGc, unita((maxl - Math.round(minl)) / 2), 0.5, canvash / 2 + canvash / 20 * 2 + canvash / 7.5);
            // 分时线
            oGc.beginPath();
            oGc.strokeStyle = '#2f5895';
            oGc.lineWidth = 2;
            oGc.moveTo(1, canvash / 4 + canvash / 4 / (data.fp * percent) * (data.fp - data.data[0][0]));
            chart_info[1].push(data.data[0][0]);
            // 循环写下一个点的坐标
            for (i = 1; i < data.data.length - 1; i++) {
              var topp = canvash / 4 + canvash / 4 / (data.fp * percent) * (data.fp - data.data[i][0]);
              oGc.lineTo(i * canvasw / 240, topp);
              chart_info[1].push(data.data[i][0]);
              fenshi_last_point = [i * canvasw / 240, topp];
            }
            oGc.stroke();
            // 均价线
            oGc.beginPath();
            oGc.strokeStyle = '#f5bc49';
            oGc.lineWidth = canvasw / 240;
            oGc.moveTo(1, canvash / 4 + canvash / 4 / (data.fp * percent) * (data.fp - data.data[0][3]));
            chart_info[2].push(data.data[0][3]);
            //循环写均价下一个点的坐标
            for (i = 1; i < data.data.length - 1; i++) {
              oGc.lineTo(i * canvasw / 240, canvash / 4 + canvash / 4 / (data.fp * percent) * (data.fp - data.data[i][3]));
              chart_info[2].push(data.data[i][3]);
            }
            oGc.stroke();
            //成交量
            oGc.beginPath();
            var bij;
            for (i = 1; i < data.data.length; i++) {
              //根据当前点的值跟上一个时间点的值做比较给出当前立柱的颜色
              if (i - 1 <= 0) {
                bij = data.fp * 100;
              } else {
                bij = data.data[i - 1][0] * 100;
              }
              if (data.data[i][0] * 100 > bij) {
                oGc.fillStyle = '#f60300';
              } else if (data.data[i][0] * 100 < bij) {
                oGc.fillStyle = '#30ae0e';
              } else {
                oGc.fillStyle = '#888888';
              }
              //生成立柱
              var Recttop = canvash - canvash * 7 / 60 - (canvash / 3) / (maxl - minl) * (data.data[i][2] - minl);
              var Rectheight = canvash - (canvash * 7 / 60) - Recttop - 1;
              oGc.fillRect(i * canvasw / 242, Recttop, canvasw / 240, Rectheight);
              chart_info[0].push(data.data[i][2]);
              // if (i == data.data.length - 1) {
              //   drawfont('25px', oGc, '现手:' + unita(data.data[i][2]), 190 * canvasw / 500, canvash / 2 + 90 / 4);
              // }
            }
            oGc.stroke();
          }
        }
      });
    };
  }]);

  //生成数字后面的单位的函数
  function unita(num) {
    var numLen = num.toString().length;
    if (numLen > 8) {
      num = num / 100000000;
      num = num.toFixed(2);
      return num + '亿';
    } else if (numLen > 4) {
      num = num / 10000;
      num = num.toFixed(2);
      return num + '万';
    } else {
      return num;
    }
  }

  //canvas生成虚线函数
  function getBeveling(x, y) {
    return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
  }

  function drawDashLine(context, x1, y1, x2, y2, dashLen) {
    context.beginPath();
    dashLen = dashLen === undefined ? 5 : dashLen;
    //得到斜边的总长度
    var beveling = getBeveling(x2 - x1, y2 - y1);
    //计算有多少个线段
    var num = Math.floor(beveling / dashLen);
    context.strokeStyle = '#dddddd';
    for (var i = 0; i < num; i++) {
      context[i % 2 == '0' ? 'moveTo' : 'lineTo'](x1 + (x2 - x1) / num * i, y1 + (y2 - y1) / num * i);
    }
    context.stroke();
    context.closePath();
  }

  function drawfont(size, ctx, fonts, x, y, color) {
    ctx.font = size + ' Microsoft YaHei';
    //设置字体填充颜色
    ctx.fillStyle = color || '#888888';
    //从坐标点(50,50)开始绘制文字
    ctx.fillText(fonts, x, y);
  }

  //获取鼠标相当于canvas 的坐标
  function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: (evt.clientX - rect.left) * (canvas.width / rect.width),
      y: (evt.clientY - rect.top) * (canvas.height / rect.height)
    };
  }
})(angular);
